package deployr.cli;

import static deployr.core.Files.*;
import static deployr.core.Streams.*;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import deployr.core.*;
import deployr.core.FileSystem;

public class DeployrServlet extends HttpServlet {

	private Projects projects;
	private Workspace workspace;

	public DeployrServlet() {
		this.workspace = createWorkspace(file(userDir("fs")), "user", null);
		this.projects = createProjects(workspace);
	}

	public DeployrServlet(JettyServer jettyServer) {
		this.workspace = createWorkspace(jettyServer.getJettyHome(), "user", jettyServer);
		this.projects = createProjects(workspace);
	}

	private Workspace createWorkspace(File root, String user, DeployListener deployListener) {
		return new Workspace(user, new FileSystem(root), deployListener);
	}

	private Projects createProjects(Workspace workspace) {
		return workspace.scanProjects();
	}

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Responder responder = new ResponderFactory(workspace, projects).createResponder();
		Result result = responder.respondTo(request.getMethod(), request.getRequestURI(), new InputHttp(request));

		ResultWriter writer = new ResultWriter(result);
		writer.writeTo(response);
	}
}